/*
 * Funny Language - a free style programming language.
 * Copyright (C) 2015 by fanguangping (fanguangping@163.com)
 * string.c
 */

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "string.h"

String alloc_string(int size) {
	return (String) malloc(sizeof(char) * size);
}

String *alloc_string_array(int size) {
	return (String*) malloc(sizeof(String) * size);
}

String realloc_string(String str, int size) {
	String new_str = (String) realloc(str, size * sizeof(char));
	if (new_str != NULL) {
		str = new_str;
	}
	return str;
}

String init_string() {
	String result = alloc_string(1);
	result[0] = '\0';
	return result;
}

String copy_string(String str) {
	String result = alloc_string(strlen(str) + 1);
	strcpy(result, str);
	return result;
}

int equals_string(void *a, void *b) {
	if (a == NULL && b == NULL)
		return 1;
	if (a == NULL || b == NULL)
		return 0;

	if (strcmp(a, b) == 0) {
		return 1;
	} else {
		return 0;
	}
}

String dyna_strcat(String str, String append) {
	if (append == NULL || equals_string(append, "")) {
		return str;
	}
	int length = strlen(str) + strlen(append) + 1;
	str = realloc_string(str, length);
	str = strcat(str, append);
	return str;
}

String append_char(String str, char c) {
	char *p = NULL;
	int length = strlen(str) + 2;
	str = realloc_string(str, length);
	p = str;
	while (*p)
		p++;
	*p++ = c;
	*p++ = '\0';
	return str;
}

